import {
		HLogin,
		userInfoData
	} from '@/api/user.js'
import request from '@/utils/request';
const state = {
	token: uni.getStorageSync("token") || '',
	isLogin: uni.getStorageSync("token") ? true : false, // 是否登陆
	userInfo: {}  // 用户信息
}


const getters = {
	token: state => state.token,
	isLogin: state => state.isLogin,
	userInfo: state => state.userInfo,
}

const actions = {
	silentLogin({ commit }, options, isLo = false) {
		 return new Promise((resolve, reject) => {
			 uni.login().then(res => {
				 const { code } = res
				 HLogin({code}, isLo).then(res => {
					 const userinfo = res.data.userinfo
					 commit('token', userinfo.token)
					 commit('isLogin', true)
					 !options && resolve(res)
					 options && request(options).then(res => {
						 resolve(res)
					 })
				 })
			 })
		 })
	},
	setUserInfo({ commit }) {
		userInfoData().then(res => {
			if(res.code === 1) {
				commit('userInfo', res.data)
			}
		})
	}
}

const mutations = {
	pushOut(state) {
		state.token = '';
		state.isLogin = false;
		state.userInfo = {};
		uni.removeStorageSync("token")
	},
	token(state, payload) {
		state.token = payload;
		uni.setStorageSync("token", payload);
	},
	// 登录态
	isLogin(state, data) {
		state.isLogin = data
	},
	// 用户信息
	userInfo(state, data) {
		state.userInfo = data;
	},
}

export default {
	namespaced: true,
	state,
	getters,
	actions,
	mutations
}

